var private_key;
var privateKeyTag = "de.hska.pwmanager.privatekey";
var publicKeyTag = "de.hska.pwmanager.publickey";

$(document).ready(function() {
	existKeys = $.jStorage.get("existKeys", false);
	if (existKeys == true) {
		$("#generateKeysMenu").hide();
		$("#scanCodeMenu").show();
		$("#showKeysMenu").show();
		$("#deleteKeysMenu").show();
	} else {
		$("#generateKeysMenu").show();
		$("#generateKeysMenu").addClass("ui-corner-bottom");
		$("#scanCodeMenu").hide();
		$("#showKeysMenu").hide();
		$("#deleteKeysMenu").hide();
	}

	/*
	            $.ajax({
	                   type: "POST",
	                   url: "http://192.168.1.2/~aw/index.php",
	                   data: {"data" : "dataString"},
	                   dataType: 'json',
	                   }).done(function( msg ) {
	                           alert( "Data Saved: " + msg.php_message );
	                           });       */

});

//-----------------------------------------------------------------------------------------------------------------
function generateKeys() {
	setTimeout(function() {
		$.mobile.loadingMessage = "Please wait, keys are generated ..."
		$.mobile.showPageLoadingMsg();
		window.plugins.PGSecKey.generateKeys([ privateKeyTag, publicKeyTag ],
				function(result) {
					showKeys()
					$.jStorage.set("existKeys", true);
					$("#generateKeysMenu").hide();
					$("#scanCodeMenu").show();
					$("#showKeysMenu").show();
					$("#deleteKeysMenu").show();
					$.mobile.hidePageLoadingMsg();
				}, error);
	}, 0);
}

//-----------------------------------------------------------------------------------------------------------------
function showKeys() {
	window.plugins.PGSecKey.getBase64EncodePrivateKey([ privateKeyTag ],
			privateKey, error);
	window.plugins.PGSecKey.getBase64EncodePublicKey([ publicKeyTag ],
			publicKey, error);
}

function privateKey(result) {
	$("#privateKey").val(result);
}

function publicKey(result) {
	$("#publicKey").val(result);
}

//-----------------------------------------------------------------------------------------------------------------
function deleteKeys() {
	window.plugins.PGSecKey.deleteKeys([ privateKeyTag, publicKeyTag ],
			deleteKeysSucces, error);
}
function deleteKeysSucces(result) {
	alert(result);
	$.jStorage.set("existKeys", false);
	$("#generateKeysMenu").show();
	$("#generateKeysMenu").addClass("ui-corner-bottom");
	$("#scanCodeMenu").hide();
	$("#showKeysMenu").hide();
	$("#deleteKeysMenu").hide();
}

//------------------------------------------------------------------------------
function scanCode() {
	window.plugins.PGSecKey.getBase64EncodePrivateKey([ privateKeyTag ],
			function(result) {
				private_key = result;
			}, error);

	window.plugins.barcodeScanner.scan(scannerSuccess, error);
}

function scannerSuccess(result) {
	if (result.text != "") {
		$.mobile.loadingMessage = "Please wait, your Password is decrypted ..."
		$.mobile.showPageLoadingMsg();
		setTimeout(function() {
			decrypt(result.text);
			$.mobile.hidePageLoadingMsg();

		}, 0);

	}
}

function decrypt(text) {

	var crypted = text.replace(/(\r\n|\n|\r)/gm, "");
	crypted = crypted.replace(/\s+/g, "");
	var params = certParser(private_key);

	if (params.b64) {
		key = pidCryptUtil.decodeBase64(params.b64);
		var rsa = new pidCrypt.RSA();
		//RSA decryption
		//ASN1 parsing
		asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(key));
		tree = asn.toHexTree();

		//setting the private key for encryption
		rsa.setPrivateKeyFromASN(tree);

		crypted = pidCryptUtil.decodeBase64(pidCryptUtil
				.stripLineFeeds(crypted));
		var decrypted = rsa.decrypt(pidCryptUtil.convertToHex(crypted));
		var result = '<textarea id="password" rows="10" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset">';
		result += decrypted;
		result += '</textarea>';
		$("#result").html(result);
	}
}

function pubkeyObj(pbkey){
    this.pubkey=pbkey;
}

function exportKeys() {
    alert('starting to ' + $('#url').val());
    var username = $('#username').val();
    var password = $('#password').val();
    var pubkeyStr = $('#publicKey').val();
    var pubkeyObj ={
        'pubkey': pubkeyStr
    };
    var loginObj = {
      'username': username,
      'password': password
    };
    
    var res = false;
    $.ajax({
           url : $('#url').val() + "login/login_user",
           type : 'POST',
           async: false,
           data : JSON.stringify(loginObj, null, '\t'),
           dataType : 'json',
           contentType : "application/json; charset=utf-8",
           success : function(result) {
           res = result;
           }
     });
    if(res) {
    $.ajax({
           url : $('#url').val() + "login/change_pubkey",
           type : 'POST',
           async: false,
           data : JSON.stringify(pubkeyObj, null, '\t'),
           dataType : 'json',
           contentType : "application/json; charset=utf-8",
           success : function(result) {
           alert('updated key');
           }
           });
    } else {
        alert('wrong username or pw');
    }
    // okay now send the rubbish to the server
}

//------------------------------------------------------------------------------
function error(error) {
	alert("Error : \r\n" + error);
	$.mobile.hidePageLoadingMsg();
}
//------------------------------------------------------------------------------
function certParser(cert) {
	var lines = cert.split('\n');
	var read = false;
	var b64 = false;
	var end = false;
	var flag = '';
	var retObj = {};
	retObj.info = '';
	retObj.salt = '';
	retObj.iv;
	retObj.b64 = '';
	retObj.aes = false;
	retObj.mode = '';
	retObj.bits = 0;
	for ( var i = 0; i < lines.length; i++) {
		flag = lines[i].substr(0, 9);
		if (i == 1 && flag != 'Proc-Type' && flag.indexOf('M') == 0)//unencrypted cert?
			b64 = true;
		switch (flag) {
		case '-----BEGI':
			read = true;
			break;
		case 'Proc-Type':
			if (read)
				retObj.info = lines[i];
			break;
		case 'DEK-Info:':
			if (read) {
				var tmp = lines[i].split(',');
				var dek = tmp[0].split(': ');
				var aes = dek[1].split('-');
				retObj.aes = (aes[0] == 'AES') ? true : false;
				retObj.mode = aes[2];
				retObj.bits = parseInt(aes[1]);
				retObj.salt = tmp[1].substr(0, 16);
				retObj.iv = tmp[1];
			}
			break;
		case '':
			if (read)
				b64 = true;
			break;
		case '-----END ':
			if (read) {
				b64 = false;
				read = false;
			}
			break;
		default:
			if (read && b64)
				retObj.b64 += pidCryptUtil.stripLineFeeds(lines[i]);
		}
	}
	return retObj;
}
